package com.example.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.example.reggie.commen.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by jinkun.tian on 2023/4/6
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1. 请求放行
        String requestURI = request.getRequestURI();

        // 定义不需要处理的URI
        String[] urls = new String[]{
                "/employee/login"
        };

        // 放行判断
        boolean check = check(urls, requestURI);

        if(check){
            log.info("本次请求{}不需要进行登录验证",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        if(request.getSession().getAttribute("employee") != null){
            log.info("用户已经登录，用户id为:{}", request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }

        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public static final AntPathMatcher PATH_PATTERN = new AntPathMatcher();

    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_PATTERN.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
